package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @authar by xiecong
 * @Date 2022/3/7
 * @Description
 */
@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {
    @Autowired
    Configuration configuration;

    @Resource(name = "minIOFileStorageService")
    private FileStorageService fileStorageService;

    @Autowired
    AuthorMapper authorMapper;

    @Value("${file.minio.prefix}")
    private String prefix;

    @Autowired
    ApArticleMapper apArticleMapper;

    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        try {
            //1.获取template模板
            Template template = configuration.getTemplate("article.ftl");
            //2.准备用于替换模板的数据
            HashMap<String, Object> map = new HashMap<>();
            // 文章信息
            map.put("article", apArticle);
            // 文章详情
            map.put("content", JSON.parseArray(content, Map.class));
            //作者对应的apUserId
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            map.put("authorApUserId", apAuthor.getUserId());
            //3.替换模板，得到替换后的内容
            StringWriter stringWriter = new StringWriter();
            template.process(map, stringWriter);
            InputStream is = new ByteArrayInputStream(stringWriter.toString().getBytes());
            //4.生成页面把html文件上传到minio中
            //路径
            String path = fileStorageService.store(prefix,
                                        apArticle.getId() + ".html",
                                        "text/html", is);
            //保存static_url字段
            apArticle.setStaticUrl(path);
            //修改ap_article表
            apArticleMapper.updateById(apArticle);

             log.info("文章详情静态页生成成功 staticUrl=====> {}", path);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文章详情静态页生成失败=====>articleId : {}    ========> {}"
                    , apArticle.getId(), e.getCause());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "文章详情静态页生成失败");
        }
    }
}
